package com.riguz.forks.framework.mvc.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.riguz.forks.framework.Framework;
import com.riguz.forks.framework.mvc.Result;
import com.riguz.forks.framework.mvc.ViewResolver;
import com.riguz.forks.framework.mvc.view.ErrorResult;
import com.riguz.forks.framework.mvc.view.JsonResult;
import com.riguz.forks.framework.mvc.view.Redirect;
import com.riguz.forks.framework.mvc.view.View;
import com.riguz.forks.framework.util.JsonUtil;
import com.riguz.forks.framework.util.ServletUtil;

public class DefaultViewResolver implements ViewResolver {
    private static final Logger logger = LoggerFactory.getLogger(DefaultViewResolver.class);
    
    @Override
    public void resolveView(HttpServletRequest request, HttpServletResponse response, Result model) throws Exception {
        if(model instanceof View)
            this.handleView(request, response, (View)model);
        else if (model instanceof JsonResult) 
            this.handleJsonResult(request, response, (JsonResult)model);
        else if (model instanceof Redirect)
            this.handleRedirect(request, response, (Redirect)model);
        else if(model instanceof ErrorResult)
            this.handleError(request, response, (ErrorResult)model);
    }

    protected void handleJsonResult(HttpServletRequest request, HttpServletResponse response, JsonResult model) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding(Framework.ENCODING);
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtil.toJSON(model.getData()));
        writer.flush();
        writer.close();
    }

    protected void handleRedirect(HttpServletRequest request, HttpServletResponse response, Redirect model) throws IOException {
        String path = model.getPath();
        if (!path.startsWith("/")) path = request.getContextPath() + path;
        response.sendRedirect(path);
    }

    protected void handleError(HttpServletRequest request, HttpServletResponse response, ErrorResult model) throws IOException {
        response.sendError(model.getCode(), model.getMessage());
    }
    
    protected void handleView(HttpServletRequest request, HttpServletResponse response, View model) throws IOException {
        String pagePath = Framework.JSP_PATH + model.getPath();
        Map<String, Object> data = model.getParameters();
        if (data != null) {
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                request.setAttribute(entry.getKey(), entry.getValue());
            }
        }
        ServletUtil.forward(request, response, pagePath);
    }
}
